package com.cat.dataStructure02;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/zero-array-transformation-ii/description/
 * @create 2025/10/23 16:46
 * @since JDK17
 */

public class Solution53 {
    boolean check(int[] nums, int[][] q, int k) {
        int n = nums.length, sum = 0;
        int[] diff = new int[n + 1];
        for (int i = 0; i < k; i++) {
            diff[q[i][0]] += q[i][2];
            diff[q[i][1] + 1] -= q[i][2];
        }
        for (int i = 0; i < n; i++) {
            sum += diff[i];
            if (sum < nums[i]) {
                return false;
            }
        }

        return true;
    }

    public int minZeroArray(int[] nums, int[][] queries) {
        int l = -1, r = queries.length + 1, mid;
        while (l + 1 < r) {
            mid = l + r >> 1;
            if (check(nums, queries, mid)) {
                r = mid;
            } else {
                l = mid;
            }
        }

        return r == queries.length + 1 ? -1 : r;
    }
}
